package com.demo.crm.springboot3security.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.crm.springboot3security.entity.CustomForm;
import com.demo.crm.springboot3security.mapper.CustomFormMapper;
import com.demo.crm.springboot3security.service.CustomFormService;
import com.mybatisflex.core.query.QueryWrapper;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class CustomFormServiceImpl implements CustomFormService {
    @Autowired
    private final CustomFormMapper customFormMapper;

    @Override
    @Transactional
    public CustomForm createForm(CustomForm form) {
        form.setCreatedAt(LocalDateTime.now());
        form.setUpdatedAt(LocalDateTime.now());
        customFormMapper.insert(form);
        return form;
    }

    @Override
    public CustomForm findByCode(String code) {
        return customFormMapper.findByCode(code);
    }

    @Override
    public CustomForm findById(Long id) {
        return customFormMapper.selectOneById(id);
    }

    @Override
    public List<CustomForm> findAll() {
        return customFormMapper.selectAll();
    }

    @Override
    public List<CustomForm> findByModuleId(Long moduleId) {
        QueryWrapper query = QueryWrapper.create().where("module_id = ?", moduleId);
        return customFormMapper.selectListByQuery(query);
    }

    @Override
    @Transactional
    public CustomForm updateForm(CustomForm form) {
        form.setUpdatedAt(LocalDateTime.now());
        customFormMapper.update(form);
        return form;
    }

    @Override
    @Transactional
    public void deleteForm(Long id) {
        customFormMapper.deleteById(id);
    }

    @Override
    public boolean existsByCode(String code) {
        QueryWrapper query = QueryWrapper.create().where("code = ?", code);
        return customFormMapper.selectCountByQuery(query) > 0;
    }

    @Override
    public List<CustomForm> findPublished() {
        QueryWrapper query = QueryWrapper.create().where("published = ?", true);
        return customFormMapper.selectListByQuery(query);
    }

    @Override
    public List<CustomForm> findByModuleIdAndPublished(Long moduleId, boolean published) {
        QueryWrapper query = QueryWrapper.create().where("module_id = ?", moduleId).and("published = ?", published);
        return customFormMapper.selectListByQuery(query);
    }
}